<template>
  <div class="compact-container">
    <!-- Compact search row with Add button on the right -->
    <div class="search-row">
      <span class="search-label">供应商昵称（编号）：</span>
      <el-input v-model="Po_VendorName" size="small" class="search-input" />
      <span class="search-label">采购订单昵称（编号）：</span>
      <el-input v-model="Po_Name" size="small" class="search-input" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table 
        :data="flattenedData" 
        border 
        style="width: 100%"
        :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }"
        :row-style="{ height: '36px' }"
        :span-method="objectSpanMethod"
        v-loading="loading"
      >
        <!-- Table columns (same as original) -->
        <el-table-column fixed width="180px" prop="po_Code" label="订单编号">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row)">{{ scope.row.po_Code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="po_State" label="采购状态" width="90px">
          <template #default="{row}">
            {{ row.po_State === 0 ? '未完成' : row.po_State === 2 ? '部分入库':row.po_State === 8 ? '未入库':row.po_State === 7 ? '部分退货':row.po_State === 6 ? '超额退货' :row.po_State === 9 ? '全部退货' : '全部入库' }}
          </template>
        </el-table-column>
        <el-table-column prop="po_Name" label="采购订单昵称" width="180px" />
        <el-table-column prop="po_Vendor_Name" label="供应商" width="180px" />
        <el-table-column prop="pro_name" width="150px" label="产品昵称" />
        <el-table-column prop="pro_model" width="150px" label="规格型号" />
        <el-table-column prop="pro_brand" width="120px" label="品牌" />
        <el-table-column prop="po_number" width="100px" label="采购数量" align="right">
          <template #default="{row}">{{ row.po_number.toFixed(0) }}</template>
        </el-table-column>
        <el-table-column prop="details_monovalent" width="120px" label="单价" align="right">
          <template #default="{row}">{{ row.details_monovalent.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column label="小计" width="120px" align="right">
          <template #default="{row}">{{ (row.po_number * row.details_monovalent).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="po_Starttime" label="采购日期" width="180px" />
        <el-table-column prop="contacts_Name" label="联系人" width="120px" />
        <el-table-column prop="contacts_Phone" label="联系方式" width="130px" />
        <el-table-column prop="po_Rep_Id" label="采购负责人" width="120px">
          <template #default="scope">{{ userValue(scope.row.po_Rep_Id) }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_Code" label="入库仓库" width="150px" />
        <el-table-column prop="po_Audit" label="是否审核" width="100px">
          <template #default="{row}">{{ row.po_Audit === '1' ? '已审核' : '未审核' }}</template>
        </el-table-column>
        <el-table-column prop="operation" fixed="right" label="操作" width="240px">
          <!-- <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template> -->
          <template #default="scope">
            <div class="action-group">
              <el-button 
                size="small" 
                @click="handleEdit(scope.row)"
                :disabled="scope.row.po_Audit === '1' || scope.row.po_Audit === '2'"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="handAudit(scope.row)"
                :disabled="scope.row.po_Audit === '1' || scope.row.po_Audit === '2'"
              >
                审核
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
                :disabled="scope.row.po_Audit === '1' || scope.row.po_Audit === '2'"
              >
                删除
              </el-button>
               <el-button size="small" type="danger" @click="handleRevoke(scope.row)"
                :disabled="scope.row.po_Audit === '0' || scope.row.details_storage !== 0 || scope.row.podet_retqty !== 0">
                撤销
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination
          small
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close1">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
import { ref, onMounted, markRaw } from 'vue';
import { Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { useStore } from 'vuex'
import { WarnTriangleFilled } from '@element-plus/icons-vue'

export default {
  setup() {

    const store = useStore()

    const Router = useRouter();
    const tableData = ref([])
    const flattenedData = ref([])
    const spanArr = ref([])
    const Po_Name = ref("")
    const Po_VendorName = ref("")
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const loading = ref(false)
    const userOptions = ref([])
    const centerDialogVisible = ref(false);//审核拟态框
    const auditStatus = ref('1');//审核状态
    const auditOpinion = ref('');//审核意见
    const po_audit_id = ref(0);//保存审核的id

    onMounted(() => {
      fill()
      count()
      getUser()
    })




    function handAudit(row){
            if (row.po_Audit==0) {
              po_audit_id.value=row.po_Id
              // console.log(row.po_Id)
                centerDialogVisible.value = true
            }else{
              // console.log(row)
                ElMessage.warning('该订单已被审核，不可再次审核！')
            }
        }
        //关闭审核框
        function close1(){
            centerDialogVisible.value = false
            auditStatus.value = '1'
            auditOpinion.value = ''
        }
        function updateAudit(){
            console.log("进来了")
            // console.log(po_audit_id.value)
            axios.put("http://localhost:5181/api/Po/PutPoUpdateAudit", {
                po_Id: po_audit_id.value,
                po_Audit_By: localStorage.getItem('userLName'),
                po_Audit_Time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                po_Audit_Remark: auditOpinion.value,
                po_Audit: auditStatus.value
            }, {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    if (auditStatus.value == '1') {
                        ElMessage.success('审核通过')
                    } else if (auditStatus.value == '2') {
                        ElMessage.warning('审核已被驳回！')
                    }
                    close1()
                    query();
                    // customer_handleClose()
                }
            }).catch((err) => {
                console.info(err)
            });
        }
    
    async function fill() {
      loading.value = true
      try {
        const result = await axios.get("http://localhost:5181/api/Po/GetPoFYWhere", {
          params: {
            Po_VendorName: Po_VendorName.value,
            Po_Name: Po_Name.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
          },
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        const formattedData = result.data.map(item => ({
          ...item,
          po_Starttime: formatDate(item.po_Starttime),
          po_Endtime: formatDate(item.po_Endtime),
          po_Audit_Time: formatDate(item.po_Audit_Time),
          create_Time: formatDate(item.create_Time),
          update_Time: formatDate(item.update_Time)
        }))
        tableData.value = formattedData
        flattenedData.value = processData(formattedData)
      } catch (err) {
        console.error(err)
        ElMessage.error('数据加载失败')
      } finally {
        loading.value = false
      }
    }

    async function count() {
      try {
        const result = await axios.get("http://localhost:5181/api/Po/GetPoCount", {
          params: {
            Po_VendorName: Po_VendorName.value,
            Po_Name: Po_Name.value,
          },
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        pageCount.value = result.data
      } catch (err) {
        console.error(err)
      }
    }

    async function getUser() {
      try {
        const result = await axios.get("http://localhost:5181/api/User/GetUsers", {
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        userOptions.value = result.data
      } catch (err) {
        console.error(err)
      }
    }

    function userValue(row) {
      if (!row) return "无";
      const parentUser = userOptions.value.find((user) => user.user_id == row)
      return parentUser ? parentUser.user_name : "无"
    }

    const processData = (data) => {
      const flatData = []
      spanArr.value = []
      
      data.forEach(order => {
        const details = order.details || []
        let totalQty = 0
        
        if (details.length > 0) {
          details.forEach(detail => {
            totalQty += detail.po_number || 0
            flatData.push({
              ...order,
              ...detail,
              key: `${order.po_Id}_${detail.details_id}`
            })
          })
          spanArr.value.push(details.length + 0)
        } else {
          flatData.push({
            ...order,
            key: `${order.po_Id}`
          })
          spanArr.value.push(1)
        }
      })
      
      return flatData
    }
    
    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      const mergeColumns = [
        'po_Code', 'po_State','po_Name', 'po_Starttime', 'po_Vendor_Name', 
        'contacts_Name', 'contacts_Phone', 'po_Rep_Id', 'warehouse_Code', 'po_Audit','operation'
      ]
      
      if (row.isSummary) {
        if (mergeColumns.includes(column.property)) {
          return { rowspan: 0, colspan: 0 }
        }
        return { rowspan: 1, colspan: 1 }
      }
      
      if (mergeColumns.includes(column.property)) {
        const position = getRowPosition(rowIndex)
        
        if (position.rowspan > 0) {
          return {
            rowspan: position.rowspan,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    }
    
    const getRowPosition = (rowIndex) => {
      let current = 0
      for (let i = 0; i < spanArr.value.length; i++) {
        const rowCount = spanArr.value[i]
        if (rowIndex < current + rowCount) {
          return {
            rowspan: rowIndex === current ? rowCount : 0,
            colspan: 1
          }
        }
        current += rowCount
      }
      return { rowspan: 1, colspan: 1 }
    }
    
    function formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }
    
    function query() {
      currentPage.value = 1
      fill()
      count()
    }
    
    function infoPage(row){
      store.commit('PO_UpdeteArray', row)
      Router.push({
        path: '/main/Pinv/PoInfo',
        // query: { rowData: JSON.stringify(row) }
      })
    }
    
    function reset() {
      Po_VendorName.value = ""
      Po_Name.value = ""
      query()
    }
    
    function addEdit() {
      Router.push({ path: '/main/Pinv/PoAdd' })
    }
    
    function handleEdit(row) {
      console.log(row)
      if(row.po_Audit != 0) {
        ElMessage.error('此订单已审核，不能修改！')
      } else {
        store.commit('PO_UpdeteArray', row)
        Router.push({
          path: '/main/Pinv/PoUpdate',
          // query: { rowData: JSON.stringify(row) }
        })
      }
    }
    
    function handleDelete(row) {
      if(row.po_Audit != 0){
        ElMessage.error('此订单已审核，不能删除！')
      }else{
        ElMessageBox.confirm(
          '此操作将删除该产品信息，是否继续？',
          '警告',
          {
            type: 'warning',
            icon: markRaw(Delete),
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }
        )
        .then(() => {
          return axios.put('http://localhost:5181/api/Po/PutPoDelete', {
            po_Id: row.po_Id,
            del_flag: "1"
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          })
        })
        .then((result) => {
          if (result.data>0) {
            ElMessage.success("删除成功")
            fill()
            count()
          } else {
            ElMessage.error("删除失败")
          }
        })
        .catch((error) => {
          console.error("删除失败:", error)
        })
      }
    }
    
    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }
    
    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function handleRevoke(row) {
      ElMessageBox.confirm(
        '此操作将删除该销售订单，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(WarnTriangleFilled),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
        .then(() => {
          axios.put('http://localhost:5181/api/Po/Pinv_PoRevoke', {
            po_Id:row.po_Id,
            po_Audit:'0'
          }).then((result) => {
            if (result.data > 0) {
              ElMessage.success('撤销成功！')
              fill()
              count()
            }
          }).catch((err) => {
            console.error(err)
          })
        })
        .catch(() => {
          ElMessage.info('已取消撤销')
        })
    }
    
    return {
      currentPage,
      Po_Name,
      tableData,
      flattenedData,
      Po_VendorName,
      pageCount,
      pageSize,
      loading,
      userOptions,
      centerDialogVisible,
      auditStatus,
      auditOpinion,
      po_audit_id,
      handleRevoke,
      updateAudit,
      handAudit,
      close1,
      handleSizeChange,
      handleCurrentChange,
      addEdit,
      query,
      handleEdit,
      handleDelete,
      reset,
      objectSpanMethod,
      infoPage,
      userValue
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

/* Compact search row with Add button on the right */
.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -50px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

/* Table area */
.table-wrapper {
  margin-top: 6px;
}

/* Compact table styles */
:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}

/* Centered pagination */
.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

/* Summary row style */
:deep(.el-table .summary-row) {
  background-color: #f0f9eb;
  font-weight: bold;
}
</style>